/*
 *  spa.view.js
 *  데이터베이스에 저장된 기사를 출력하는 모듈
 */

spa.view = (function() {
/*-----------------------Module Variable Start----------------------*/
  var configMap = {
    main_html : String()
      + 'It is main view',
    article_scroll_up_time: 150,
    article_scroll_down_time: 150
  },
  stateMap = {
    $container : null,
    $article_modal : null,
    $article_nav : null,
    article_map : null
  },
  jqueryMap = {},
  initModule,         setJqueryMap,       renderArticleTile,
  onArticleMouseOver, onArticleMouseOut,  onArticleClick,
  renderArticle, renderArticleNav, renderArticlePagination,
  renderComment;
/*-----------------------Module Variable End------------------------*/
    
/*-----------------------Utility Method Start-----------------------*/
/*-----------------------Utility Method End-------------------------*/

/*-----------------------DOM Method Start---------------------------*/
  // /setJqueryMap/ Start
  setJqueryMap = function() {
    var $container = stateMap.$container,
        $article_modal = stateMap.$article_modal,
        $article_nav = stateMap.$article_nav
    jqueryMap = {
      $container : $container,
      $article_modal : $article_modal,
      $article_nav : $article_nav
    };
  };
  // /setJqueryMap/ End
  
  // /renderArticleTile/ Start
  // 목적   : json 형태의 기사를 받아 페이지에 타일 형태로 출력
  // 인자   : - arti_map : 각각의 기사가 저장된 json
  // 상태   : article_map 업데이트
  // 반환값 : 성공 시 true, 실패 시 false 반환
  // 행동   :
  //          1.  기사 맵이 전과 다른지 점검해서 다를 때만 진행
  //          2.  json 맵에서 각각의 타일을 html 형식으로 파싱한다.
  //              - 각 타일은 기본적으로 사진과 제목을 보여준다.
  //              - 마우스 오버시 배경사진을 없애고 간단한 설명을
  //                보여준다.
  //              - 마우스 클릭시 해당 기사의 모달팝업을 띄운다.
  //          3.  파싱된 html으로 컨테이너를 새로고침한다.
  renderArticleTile = function(arti_map) {
    var is_update = ( !stateMap.article_map ||
                      arti_map !== stateMap.article_map ),
        article_id, article, article_html, previous_article_date
        revise_html = String()+ '<div class="spa-view-tiles">';
    if (!is_update) {return false;}
    stateMap.article_map = arti_map;
    //각각의 기사를 html로 파싱하여 새로운 html에 덧붙임.
    for (var i = 0; i < arti_map.length; i++) {
        article = arti_map[i];
        var pubtimeSplit = article.pubtime.split(new RegExp(' |:', 'g')),
            article_date = pubtimeSplit[0] + "-" + pubtimeSplit[1] + "-" + pubtimeSplit[2];
        if (!previous_article_date || previous_article_date !== article_date) {
          revise_html = revise_html
            + '<div class="spa-view-date">'
              + '<h1 class="spa-view-date-title">' + article_date + '</h1>'
              + '<div class="spa-view-date-line"></div>'
            + '</div>'
          ;
            
        }

        article_html = String()
          + '<div id="' + article.aid + '" class="spa-view-article" '
          + 'style="background-image:url(' + article.thumb + '); background-size: cover;'
          + 'background-repeat: no-repeat">'
            + '<div class="spa-view-article-wrap">'
              + '<div class="spa-view-article-context"><p>' + article.cont + '</p></div>'
            + '</div>'
            + '<div class="spa-view-article-title"><p>'+ article.title +'</p></div>'
          + '</div>'
        ;
      
        revise_html = revise_html + article_html;
        previous_article_date = article_date;
    }

    revise_html = revise_html + '</div>';
    configMap.main_html = revise_html;
    stateMap.$container.html(revise_html);
    
    //기사 개체에다가 이벤트 핸들러 부착
    $('.spa-view-article')
      .on('click', onArticleClick)
      .hover(onArticleMouseOver, onArticleMouseOut);
    
  };
  // /renderArticleTile/ End
  // /renderArticleNav/ Start
  renderArticleNav = function() {
    nav_html = String()
      + '<h3>Category</h3>'
      + '<ul class="spa-view-category">'
        + '<li><a href="javascript:spa.shell.onCategoryClick()">전체</a></li>'
        + '<li><a href="javascript:spa.shell.onCategoryClick(1)">정치</a></li>'
        + '<li><a href="javascript:spa.shell.onCategoryClick(2)">사회</a></li>'
        + '<li><a href="javascript:spa.shell.onCategoryClick(3)">경제</a></li>'
        + '<li><a href="javascript:spa.shell.onCategoryClick(4)">국제</a></li>'
        + '<li><a href="javascript:spa.shell.onCategoryClick(5)">의학과학</a></li>'
        + '<li><a href="javascript:spa.shell.onCategoryClick(6)">문화연예</a></li>'
        + '<li><a href="javascript:spa.shell.onCategoryClick(7)">스포츠</a></li>'
      + '</ul>';

    stateMap.$article_nav.html(nav_html);
  }
  // /renderArticleNav/ End
/*-----------------------DOM Method End-----------------------------*/
    
/*-----------------------Event Handler Start------------------------*/
  // /onArticleClick/ Start
  onArticleClick = function(e) {
    spa.shell.changeAnchorPart({
      modal: (spa.shell.isModalActivated ? "article" : "deactivated"),
      _modal : {
        id : $(this).attr("id")
      }
    });
    $(this).trigger('mouseleave');
  };
  // /onArticleClick/ End
  
  // /onArticleMouseOver/ Start
  onArticleMouseOver = function(e) {
    var $wrap = $(this).find('.spa-view-article-wrap'),
        $title = $(this).find('.spa-view-article-title');
   
    $title.animate({height: "0px"}, configMap.article_scroll_up_time, function() {
      $title.hide();
      $wrap.show().animate({height: "100%"}, configMap.article_scroll_down_time);
    });
  };
  // /onArticleMouseOver/ End
  //
  // /onArticleMouseOut/ Start
  onArticleMouseOut = function(e) {
    var $wrap = $(this).find('.spa-view-article-wrap'),
        $title = $(this).find('.spa-view-article-title');

    $wrap.animate({height: "0px"}, configMap.article_scroll_up_time, function() {
      $wrap.hide();
      $title.show().animate({height: "100%"}, configMap.article_scroll_down_time);
    });
  };
  // /onArticleMouseOut/ End
/*-----------------------Event Handler End--------------------------*/

/*-----------------------Public Method Start------------------------*/
  // /initModule/ Start
  initModule = function($container, $article_modal, $article_nav) {
    stateMap.$container = $container;
    stateMap.$article_modal = $article_modal;
    stateMap.$article_nav = $article_nav
    $container.html(configMap.main_html);
    setJqueryMap();

    renderArticleNav();
    spa.model.article.getList();
  };
  // /initModule/ End
  // /renderArticle/ Start
  // 목적   : 어느 특정한 Article 객체를 전달받아 그것을 렌더링한 html를
  //          만들어서 반환한다.
  // 인자   : - article : 렌더링할 Article 모델의 한 객체
  // 상태   :
  // 반환값 : String (HTML)
  // 행동   : 
  //          1. 전달받은 JSON을 파싱, 정해진 양식에 대입함.
  //          2. 완성된 HTML을 반환함.
  renderArticle = function(article) {
   var revise_html,
       parsingContent = article.cont.replace(/\\n/gi, '<br>').replace(/\\\"|\\\'/g, '"');
   revise_html = String()
    + parsingContent;
    jqueryMap.$article_modal.html(revise_html).find("img").after("<br>");
    spa.model.comment.getComment(article.aid);
    return true;
  };
  // /renderArticle/ End
  // /renderArticlePaginateion/ Start
  renderArticlePagination = function( category, title, page ) {
    var font_color = ""
    $.ajax({
      type: "POST",
      url: "jsp/ArticleListPageCount.jsp",
      data: {
        "category" : category,
        "title" : title,
        "page" : page
      },
      dataType: "json",
      success : function( response ) {
        var page_html = String()
          + '<ul class="spa-view-pagination">';
          for(var i = 1; i <= response.page; i++){
            if (i === spa.model.article.getNowPage()) {
              font_color = "color:#41A541";
            }
            else {
              font_color = "";
            }
            
            page_html = page_html 
              + '<li onclick="spa.model.article.getList('+ i+ ','
                + spa.model.article.getNowCategory() + ','
                + spa.model.article.getNowTitle()
              + ')" style="' + font_color + '">'+ i +'</li>'
          }
          page_html += '</ul>';
        $(".spa-view-pagination").remove();
        $(".spa-view-tiles").after(page_html);
      }
    });
  }
  renderComment = function( comment_json, article_id ) {
    var comment_html = String()
      + '<div class="spa-view-comment">'
        + '<div class="spa-view-comment-input">'
          + '<textarea></textarea>'
          + '<div class="btn-comment-submit"><span class="glyphicon glyphicon-pencil"></span></div>'
          + '<div class="clear-both"></div>'
        + '</div>'
        + '<div class="spa-view-comment-contents">'

    for(var i = 0; i < comment_json.length; i++) {
      var comment = comment_json[i],
          parsed_comment_text = comment.c_text.replace(/\n/ig, '<br>');
      comment_html = comment_html
        + '<div id="comment_' + comment.c_id + '" class="spa-view-comment-wrap">'
          + '<div  class="spa-view-comment-header">'
            + '<p>' + comment.c_id_u + '</p>' 
            + '<p>' + comment.c_date + '</p>'
            + '<div class="clear-both"></div>'
          + '</div>'
          + '<div class="spa-view-comment-text">'
            + parsed_comment_text
          + '</div>'
        + '</div>'
        ;
    }

    comment_html += '</div></div>';
    $('.spa-view-comment').remove();
    $('.spa-shell-article_modal > div').append(comment_html);
    $('.btn-comment-submit').on("click", function(e) {
        var text = $('.spa-view-comment-input textarea').val(),
            aid = article_id;

        spa.model.comment.saveComment( aid, text );
    });
  }
  // /renderArticlePaginateion/ End
/*-----------------------Public Method End--------------------------*/
  // Return public function
  return  {
            initModule : initModule,
            renderArticle : renderArticle,
            renderArticleTile : renderArticleTile,
            renderArticlePagination : renderArticlePagination,
            renderComment : renderComment
          };
}());
